package com.aurora.azurstarter

import com.orhanobut.logger.Logger
import java.io.DataOutputStream
import java.io.IOException
import java.io.OutputStream
import java.lang.Exception

class RootUtils {
    fun su(cmd: String) {
        try {
            val process = Runtime.getRuntime().exec("su")

            val os = DataOutputStream(process.outputStream)
            os.write("$cmd\n".toByteArray())
            os.flush()
            os.close()

            val hr = process.waitFor()
            Logger.d("Su returns: $hr")
            if(hr != 0)
                throw Exception("Can't get root permission: su returns $hr!")
        } catch (e: Exception) {
            Logger.e("无法获取 ROOT 权限.")
            throw e
        }
    }

    companion object {
        private var rootUtils: RootUtils? = null;

        fun instance() : RootUtils
        {
            if(rootUtils == null) {
                synchronized(RootUtils::class.java) {
                    if(rootUtils == null)
                        rootUtils = RootUtils();
                }
            }
            return rootUtils!!
        }
    }
}

